'''
Author: WangNing
Date: 2025-04-25 20:28:56
LastEditors: WangNing
LastEditTime: 2025-04-26 14:24:07
FilePath: \\linetest\\backend\\app.py
Description: 任务拆分管理系统API
Copyright (c) 2025 by VGE, All Rights Reserved. 
'''

from flask import Flask, request, jsonify, g
import psycopg2
from psycopg2.extras import RealDictCursor
import json
import os
from datetime import datetime
import openai
from config.config import DB_CONFIG, OPENAI_MODEL, TASK_STATUS, TASK_BREAKDOWN_CONFIG, get_openai_api_key
from flask_swagger_ui import get_swaggerui_blueprint
import time
from flask_cors import CORS  # 导入CORS

# 导入模块化路由
from api.project_routes import project_bp
from api.task_routes import task_bp
from api.execution_routes import execution_bp
from api.dependency_routes import dependency_bp
from api.progress_routes import progress_bp
from api.user_routes import user_bp
from api.auth_routes import auth_bp  # 导入认证路由
from api.ai_routes import ai_bp  # 导入AI服务路由
from api.dashboard_routes import dashboard_bp  # 导入仪表盘路由
from api.git_routes import git_bp  # 导入Git操作路由
from api.db_routes import db_bp  # 导入数据库操作路由

# 导入辅助函数
from utils.db import get_db, close_db, ensure_tables_exist
from utils.helpers import (
    format_tasks_tree, 
    log_task_status_change, 
    update_task_progress, 
    check_task_dependencies, 
    add_task_dependency,
    record_file_change,
    format_datetime,
    format_file_size
)
from utils.notifications import create_notification, log_ai_conversation
from services.ai_service import ai_stream_response

# 创建Flask应用
app = Flask(__name__)
CORS(app, resources={r"/api/*": {
    "origins": "*",
    "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    "allow_headers": ["Content-Type", "Authorization"]
}})  # 添加CORS支持，允许所有跨域请求

# 配置长请求超时
app.config['TIMEOUT'] = 300  # 5分钟超时
app.config['REQUEST_TIMEOUT'] = 300  # 请求超时

# 配置 Swagger UI
SWAGGER_URL = '/api/docs'  # Swagger UI的URL
API_URL = '/static/swagger.json'  # API文档的URL
swaggerui_blueprint = get_swaggerui_blueprint(
    SWAGGER_URL,
    API_URL,
    config={
        'app_name': "任务拆分管理系统API文档"
    }
)
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

# 注册各个模块化的API路由蓝图
app.register_blueprint(project_bp, url_prefix='/api')
app.register_blueprint(task_bp, url_prefix='/api')
app.register_blueprint(execution_bp)
app.register_blueprint(dependency_bp)
app.register_blueprint(progress_bp)
app.register_blueprint(user_bp)
app.register_blueprint(auth_bp)  # 注册认证路由
app.register_blueprint(ai_bp)  # 注册AI服务路由
app.register_blueprint(dashboard_bp, url_prefix='/api')  # 注册仪表盘路由
app.register_blueprint(git_bp)  # 注册Git操作路由
app.register_blueprint(db_bp)  # 注册数据库操作路由

# 创建静态文件夹（如果不存在）
os.makedirs('backend/static', exist_ok=True)
# 创建临时文件夹（如果不存在）
os.makedirs('backend/temp', exist_ok=True)

# OpenAI配置
openai.api_key = os.getenv("OPENAI_API_KEY", get_openai_api_key())

# 在请求前获取数据库连接
@app.before_request
def before_request():
    g.db = get_db(app)

# 在请求后关闭数据库连接
@app.teardown_appcontext
def close_db_connection(e=None):
    close_db()

# 获取任务的AI对话记录
@app.route('/api/tasks/<int:task_id>/ai-conversations', methods=['GET'])
def get_ai_conversations(task_id):
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    SELECT * FROM ai_conversation_logs
    WHERE related_task_id = %s
    ORDER BY created_at DESC
    ''', (task_id,))
    
    conversations = cursor.fetchall()
    
    return jsonify({
        'status': 'success',
        'data': conversations
    })

# 获取任务的通知
@app.route('/api/tasks/<int:task_id>/notifications', methods=['GET'])
def get_task_notifications(task_id):
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    SELECT * FROM notifications
    WHERE related_task_id = %s
    ORDER BY created_at DESC
    ''', (task_id,))
    
    notifications = cursor.fetchall()
    
    return jsonify({
        'status': 'success',
        'data': notifications
    })

# Swagger API文档
@app.route('/static/swagger.json')
def swagger_json():
    swagger_spec = {
        "swagger": "2.0",
        "info": {
            "title": "任务拆分管理系统API",
            "description": "通过API管理项目、任务拆分和执行过程",
            "version": "1.0.0"
        },
        "basePath": "/api",
        "schemes": ["http"],
        "consumes": ["application/json"],
        "produces": ["application/json"],
        "paths": {
            "/projects": {
                "get": {
                    "summary": "获取所有项目",
                    "description": "返回系统中的所有项目",
                    "responses": {
                        "200": {
                            "description": "成功返回项目列表",
                            "schema": {
                                "type": "object",
                                "properties": {
                                    "status": {"type": "string"},
                                    "data": {
                                        "type": "array",
                                        "items": {"$ref": "#/definitions/Project"}
                                    }
                                }
                            }
                        }
                    }
                },
                "post": {
                    "summary": "创建新项目",
                    "description": "创建一个新项目",
                    "parameters": [
                        {
                            "name": "project",
                            "in": "body",
                            "description": "项目信息",
                            "required": True,
                            "schema": {
                                "type": "object",
                                "properties": {
                                    "name": {"type": "string"},
                                    "description": {"type": "string"},
                                    "start_date": {"type": "string", "format": "date"},
                                    "end_date": {"type": "string", "format": "date"}
                                },
                                "required": ["name"]
                            }
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "成功创建项目",
                            "schema": {
                                "type": "object",
                                "properties": {
                                    "status": {"type": "string"},
                                    "data": {"$ref": "#/definitions/Project"}
                                }
                            }
                        }
                    }
                }
            }
        },
        "definitions": {
            "Project": {
                "type": "object",
                "properties": {
                    "id": {"type": "integer"},
                    "name": {"type": "string"},
                    "description": {"type": "string"},
                    "start_date": {"type": "string", "format": "date"},
                    "end_date": {"type": "string", "format": "date"},
                    "created_at": {"type": "string", "format": "date-time"},
                    "updated_at": {"type": "string", "format": "date-time"},
                    "status": {"type": "string"},
                    "tasks": {
                        "type": "array",
                        "items": {
                            "$ref": "#/definitions/Task"
                        }
                    }
                }
            },
            "Task": {
                "type": "object",
                "properties": {
                    "id": {"type": "integer"},
                    "project_id": {"type": "integer"},
                    "parent_id": {"type": "integer"},
                    "name": {"type": "string"},
                    "description": {"type": "string"},
                    "status": {"type": "string"},
                    "priority": {"type": "integer"},
                    "created_at": {"type": "string", "format": "date-time"},
                    "updated_at": {"type": "string", "format": "date-time"},
                    "is_atomic": {"type": "boolean"},
                    "estimated_hours": {"type": "number"},
                    "actual_hours": {"type": "number"},
                    "progress": {"type": "integer"},
                    "assignee": {"type": "string"},
                    "tasks": {
                        "type": "array",
                        "items": {
                            "$ref": "#/definitions/SubTask"
                        }
                    }
                }
            },
            "SubTask": {
                "type": "object",
                "properties": {
                    "id": {"type": "integer"},
                    "project_id": {"type": "integer"},
                    "parent_id": {"type": "integer"},
                    "name": {"type": "string"},
                    "description": {"type": "string"},
                    "status": {"type": "string"},
                    "priority": {"type": "integer"},
                    "created_at": {"type": "string", "format": "date-time"},
                    "updated_at": {"type": "string", "format": "date-time"},
                    "is_atomic": {"type": "boolean"},
                    "estimated_hours": {"type": "number"},
                    "actual_hours": {"type": "number"},
                    "progress": {"type": "integer"},
                    "assignee": {"type": "string"},
                    "tasks": {
                        "type": "array",
                        "items": {
                            "$ref": "#/definitions/SubTask"
                        }
                    }
                }
            }
        }
    }
    return jsonify(swagger_spec)

# 添加CORS头部和错误处理
@app.after_request
def after_request(response):
    # 允许所有域
    response.headers.add('Access-Control-Allow-Origin', '*')
    # 允许的请求头
    response.headers.add('Access-Control-Allow-Headers', 
                         'Content-Type, Authorization, X-Requested-With, X-Request-ID')
    # 允许的请求方法
    response.headers.add('Access-Control-Allow-Methods', 
                         'GET, POST, PUT, DELETE, OPTIONS, PATCH')
    # 允许携带凭证
    response.headers.add('Access-Control-Allow-Credentials', 'true')
    return response

# 错误处理器
@app.errorhandler(500)
def internal_server_error(e):
    """处理500内部服务器错误"""
    return jsonify({
        'status': 'error',
        'message': '服务器内部错误'
    }), 500

@app.errorhandler(404)
def not_found(e):
    """处理404页面未找到错误"""
    return jsonify({
        'status': 'error',
        'message': '请求的资源不存在'
    }), 404

@app.errorhandler(400)
def bad_request(e):
    """处理400错误请求"""
    return jsonify({
        'status': 'error',
        'message': '无效的请求'
    }), 400

@app.errorhandler(Exception)
def handle_unexpected_error(e):
    """处理未预期的异常"""
    app.logger.error(f'未处理的异常: {str(e)}')
    return jsonify({
        'status': 'error',
        'message': '服务器发生错误',
        'error': str(e)
    }), 500

# 服务启动入口
if __name__ == '__main__':
    # 确保数据库表存在
    ensure_tables_exist(app)
    
    # 如果不是调试模式，使用waitress作为生产级WSGI服务器
    if not app.debug:
        from waitress import serve
        port = int(os.getenv("PORT", "5000"))
        host = "0.0.0.0"
        print("="*50)
        print(f"生产模式服务器已启动")
        print(f"服务访问地址: http://localhost:{port}")
        print(f"Swagger API文档: http://localhost:{port}/api/docs")
        print("="*50)
        serve(app, host=host, port=port)
    else:
        # 开发模式下使用Flask内建服务器
        port = int(os.getenv("PORT", "5000"))
        host = "0.0.0.0"
        print("="*50)
        print(f"开发模式服务器已启动")
        print(f"服务访问地址: http://localhost:{port}")
        print(f"Swagger API文档: http://localhost:{port}/api/docs")
        print("="*50)
        app.run(host=host, port=port, debug=True)
 